<!-- 属性管理  -->
<template>
  <ContentWrap :show-border="false">
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px search-form"
      label-width="68px"
      label-position="left"
    >
      <el-form-item label="属性项" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入属性项"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item class="p-0 m-0" style="border: none !important">
        <el-button @click="handleQuery" type="primary" color="#3721FF"> 搜索 </el-button>
        <el-button style="border: none !important" @click="resetQuery">
          <Icon class="mr-5px" icon="ant-design:clear-outlined" />
          清除条件
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :show-border="false">
    <el-row :gutter="10" class="mb6">
      <el-col :span="1.5" class="el-btn">
        <el-button
          type="primary"
          color="#3721FF"
          class="add-website-btn"
          @click="handleAddClassification"
        >
          <Icon class="mr-2px" icon="ep:plus" />
          新增分类
        </el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
      class="rounded-lg"
    >
      <el-table-column label="属性项" prop="name" width="120" />
      <el-table-column
        align="center"
        label="语言"
        min-width="90"
        prop="language"
        :filters="regionFilters"
        :filter-method="filterHandler"
      >
        <template #filter-icon>
          <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="language"
        align="center"
        label="属性项（外文）"
        prop="nameForeign"
        width="180"
      />
      <el-table-column align="center" label="创建者" prop="nickName" width="180" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      />
      <el-table-column align="center" fixed="right" label="操作" class-name="all-button">
        <template #default="{ row }">
          <el-button link type="primary" color="#3721FF" plain @click="openDetail(row.id)">
            编辑
          </el-button>
          <el-button link type="danger" plain @click="handleDelete(row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <AddAttr ref="addAttrRef" @update:dialog-visible="handleUpdateDialogVisible" />
  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p>确定删除吗？</p>
    </template>
  </ComfirmPops>
</template>
<script lang="ts" setup>
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import AddAttr from './addAttr.vue'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { AttrApi } from '@/api/product/attr/index'
import { handlegetLanguageList } from '@/utils/index'
const deletePopsRef = ref()
defineOptions({ name: 'ProductSpu' })

const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const addAttrRef = ref(null) // 新增属性
const loading = ref(false) // 列表的加载中
const delSelected = ref(0)

const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const isAddCopy = ref(false) // 是否复制
const isWebsiteAnalysis = ref(false) // 是否网站解析
const copyId = ref(0) // 复制的ID
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
// tabs 数据
const tabsData = ref([
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])
// 原始数据
const tableData = ref([{ region: '北京' }, { region: '上海' }, { region: '广州' }])

// 所有可筛选的地区选项
const regionFilters = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  name: '',
  categoryId: undefined,
  createTime: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由
const getList = async () => {
  loading.value = true
  try {
    const data = await AttrApi.getPropertyList(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const goSetNavigation = () => {
  router.push({ name: 'SetNavigation' })
}
// 复制
const goCopy = (id: number) => {
  isAddCopy.value = true
  copyId.value = id
}
// 网站分析
const goWebsiteAnalysis = (id: number) => {
  isWebsiteAnalysis.value = true
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
const handleAddClassification = () => {
  addAttrRef.value.openDialog()
}
// 筛选逻辑
const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
  const property = column['property']
  return row[property] === value
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}

/** 获得每个 Tab 的数量 */
// const getTabsCount = async () => {
//   const res = await ProductSpuApi.getTabsCount()
//   for (let objName in res) {
//     tabsData.value[Number(objName)].count = res[objName]
//   }
// }
// 关闭新增
const handleUpdateDialogVisible = (val: boolean) => {
  if (!val) {
    getList()
  }
}

/** 添加到仓库 / 回收站的状态 */
// const handleStatus02Change = async (row: any, newStatus: number) => {
//   try {
//     // 二次确认
//     const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
//     await message.confirm(`确认要"${row.name}"${text}吗？`)
//     // 发起修改
//     await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
//     message.success(text + '成功')
//     // 刷新 tabs 数据
//     await getTabsCount()
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 更新上架/下架状态 */
// const handleStatusChange = async (row: any) => {
//   try {
//     // 二次确认
//     const text = row.status ? '上架' : '下架'
//     await message.confirm(`确认要${text}"${row.name}"吗？`)
//     // 发起修改
//     await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
//     message.success(text + '成功')
//     // 刷新 tabs 数据
//     await getTabsCount()
//     // 刷新列表
//     await getList()
//   } catch {
//     // 异常时，需要重置回之前的值
//     row.status =
//       row.status === ProductSpuStatusEnum.DISABLE.status
//         ? ProductSpuStatusEnum.ENABLE.status
//         : ProductSpuStatusEnum.DISABLE.status
//   }
// }

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  deletePopsRef.value.show(id)
  delSelected.value = id
}
const getDeletePops = (bool, id) => {
  AttrApi.deleteProperty(id).then((res) => {
    message.success('删除成功')
    getList()
  })
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
// const openForm = (id?: number) => {
//   // 修改
//   if (typeof id === 'number') {
//     push({ name: 'ProductSpuEdit', params: { id } })
//     return
//   }
//   // 新增
//   push({ name: 'ProductSpuAdd' })
// }

/** 查看商品详情 */
const openDetail = (id: number) => {
  addAttrRef.value.openDialog(id)
}

/** 导出按钮操作 */
// const handleExport = async () => {
//   try {
//     // 导出的二次确认
//     await message.exportConfirm()
//     // 发起导出
//     exportLoading.value = true
//     const data = await ProductSpuApi.exportSpu(queryParams.value)
//     download.excel(data, '商品列表.xls')
//   } catch {
//   } finally {
//     exportLoading.value = false
//   }
// }

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  getList()
  // 解析路由的 categoryId
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId
  }
  regionFilters.value = await handlegetLanguageList()
  // 获得商品信息
  // await getTabsCount()
  await getList()
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
